
<template>
  <div class="app-container app-container-next">
    <el-card class="box-card" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'menu-list'}">
          <el-button plain icon="el-icon-back" size="small" :round="true">
            返回
          </el-button>
        </router-link>
      </div>
      <el-row>
        <el-col :span="20">
          <el-form ref="menuForm" :model="menu" :rules="rules" label-width="120px">
            <h4>菜单信息</h4>
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="menu.name" placeholder="请输入菜单名称" style="width: 400px" maxlength="50" show-word-limit/>
            </el-form-item>
            <h4>菜单目录结构</h4>
            <dragTreeTable
                ref="table"
                :data="treeData"
                :onDrag="onTreeDataChange"
                resize
                fixed
                :isdraggable="true">
            </dragTreeTable>
            <el-button type="text" @click="handleAddRow"> <i class="el-icon-plus"></i>添加菜单目录</el-button>
            <el-form-item>
              <el-button type="primary" @click="handleSubmit('menuForm')" :loading="submitLoading">保存</el-button>
              <el-button @click="handleReset('menuForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <component v-if="showDialog !== 'home'" :is="showDialog" :productDialogVisible="isOpen" @save="getSelectData" />
  </div>
</template>

<script>
import dragTreeTable from '@/components/vue-drag-table/index';
import {updateNavigation, getNavigation} from '@/api/menu-navigation';
import seriesDialog from '_c/Dialog/series_dialog';
import productDialog from '_c/Dialog/product_dialog';
import customizeDialog from '_c/Dialog/customize_dialog';
import customUrlDialog from '_c/Dialog/custom_url_dialog';
import {mapGetters} from 'vuex';
export default {
    name: 'menu-edit',
    components: {
        dragTreeTable,
        'series_detail_page': seriesDialog,
        'product_detail_page': productDialog,
        'theme_auto': customizeDialog,
        'url_auto': customUrlDialog
    },
    data () {
        return {
            showDialog: '',
            isOpen: true,
            menuId: this.$route.params.id,
            treeData: {
                columns: [
                    {
                        type: 'input',
                        title: '<a style="font-size: 14px;">导航名称</a>',
                        field: 'name',
                        width: 360,
                        align: 'left',
                        titleAlign: 'left',
                        formatter: item => {
                            return '<span>' + item.name + '</span>';
                        }
                    },
                    {
                        type: 'select',
                        title: '<a style="font-size: 14px;">链接页面</a>',
                        field: 'resourceName',
                        width: 300,
                        align: 'center',
                        onchange: (data, model) => {
                            this.handleSetImg(data, model);
                        }
                    },
                    // {
                    //     title: '<div>移动端图片<div title="图片建议尺寸: &#10; 1.建议纵横比: 1:1(H5二级导航建议纵横比1:3) &#10; 2.上传的png/jpg/jep格式文件,大小不超过10MB" style="display: inline-block;width: 14px;height: 14px;line-height: 14px;font-size: 12px;color: #fff;background-color:#3C3C3C;border-radius: 7px;">?</div></div>',
                    //     type: 'upload',
                    //     field: 'mobileImage',
                    //     width: 160
                    // },
                    {
                        title: '<div>导航Icon<div title="图片建议尺寸: &#10; 1.建议纵横比: 1:1(H5二级导航建议纵横比1:3) &#10; 2.上传的png/jpg/jep格式文件,大小不超过10MB" style="display: inline-block;width: 14px;height: 14px;line-height: 14px;font-size: 12px;color: #fff;background-color:#3C3C3C;border-radius: 7px;">?</div></div>',
                        type: 'upload',
                        field: 'menuIcon',
                        width: 300
                    },
                    {
                        title: '<div>导航Banner<div title="图片建议尺寸: &#10; 1.建议纵横比: 1:1(H5二级导航建议纵横比1:3) &#10; 2.上传的png/jpg/jep格式文件,大小不超过10MB" style="display: inline-block;width: 14px;height: 14px;line-height: 14px;font-size: 12px;color: #fff;background-color:#3C3C3C;border-radius: 7px;">?</div></div>',
                        type: 'upload',
                        field: 'menuBanner',
                        width: 300
                    },
                    {
                        title: '<a style="font-size: 14px;">操作</a>',
                        type: 'action',
                        width: 300,
                        actions: [
                            {
                                text: '添加子节点',
                                onclick: (item) => {
                                    this.$refs.table.AddRow(item['row-key-id'], {'resourceName': '', name: '', 'row-key-id': item['row-key-id'] + +new Date()});
                                },
                                formatter: (item, index) => {
                                    return index < 2 ? '<i style="font-size: 14px;">添加子节点 </i>' : '';
                                }
                            },
                            {
                                text: '删除',
                                onclick: this.onDel,
                                formatter: item => {
                                    return '<i style="font-size: 14px;">删除</i>';
                                }
                            }
                        ]
                    }
                ],
                lists: [],
                custom_field: {
                    id: 'row-key-id',
                    parent_id: 'parent-row-key-id',
                    lists: 'navigationList',
                    order: 'sort'
                }
            },
            menu: {
                name: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入菜单名称', trigger: 'blur' }
                ]
            },
            submitLoading: false,
            submit: true
        };
    },
    computed: {
        ...mapGetters(['siteList']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        }
    },
    mounted () {
        // console.log(this.treeData);
        this.$nextTick(() => {
            this.initData();
        });
    },
    methods: {
        genID (length) {
            return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
        },
        handleAddRow () {
            this.treeData.lists.push({
                'row-key-id': this.genID(4),
                sort: 0,
                name: '',
                linkUrl: '',
                resourceName: ''
            });
        },
        menuTree (data) {
            data.forEach(res => {
                res['row-key-id'] = res.id;
                res['parent-row-key-id'] = res.parentId;
                res['open'] = true;
                if (res.navigationList) {
                    this.menuTree(res.navigationList);
                }
            });
            return data;
        },
        initData () {
            getNavigation(this.siteId, this.menuId).then(res => {
                const {data} = res;
                const navigationList = data.navigationList;
                this.menu.name = data.name;
                this.$nextTick(() => {
                    this.treeData.lists = this.menuTree(navigationList);
                });
            });
        },
        onTreeDataChange (list) {
            this.treeData.lists = list;
        },
        onDel (item) {
            this.$confirm('将删除该栏, 是否确定?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let rowId = item.id;
                if (rowId === undefined || rowId == null || rowId === '') {
                    rowId = item['row-key-id'];
                }
                const updatedLists = this.$refs.table.DelById(rowId);
                this.treeData.lists = updatedLists;
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleResponse (response, file, fileList) {
            return response;
        },
        treeListDeep (treeList) {
            this.submit = true;
            if (treeList.find((res) => res.name === '')) {
                this.submit = false;
            } else {
                treeList.forEach(item => {
                    if (item.navigationList && item.navigationList.length !== 0) {
                        this.treeListDeep(item.navigationList);
                    }
                });
            }
        },
        handleSubmit (name) {
            let treeList = this.treeData.lists;
            this.treeListDeep(treeList);
            this.$refs.table.submit();
            this.$refs[name].validate(valid => {
                if (valid && this.submit === true) {
                    this.submitLoading = true;
                    const menu = {
                        id: this.menuId,
                        siteId: this.siteId,
                        name: this.menu.name,
                        navigationList: this.treeData.lists
                    };
                    updateNavigation(this.menuId, menu).then(res => {
                        if (res.code === '200') {
                            this.submitLoading = false;
                            this.$message.success('修改成功');
                            this.$router.push({ name: 'menu-list' });
                        }
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        getSelectData (data) {
            this.isOpen = false;
            const map = {
                'series_detail_page': 'collection',
                'product_detail_page': 'goods',
                'theme_auto': 'custom-page'
            };
            if (this.showDialog !== 'url_auto' && this.showDialog !== 'home') {
                this.cacheData.linkUrl = 'https://' + this.siteInfo.domainName + `/${map[this.showDialog]}/` + data.id;
            } else if (this.showDialog === 'home') {
                this.cacheData.linkUrl = 'https://' + this.siteInfo.domainName + `/${data.resourceName}`;
            } else {
                this.cacheData.linkUrl = 'https://' + this.siteInfo.domainName + `/${data.url}`;
            }
        },
        handleSetImg (item, model) {
            model.mobileImage = item.mainImage || item.icon;
        },
        handleReset (name) {
            this.$router.push({ name: 'menu-list' });
        }

    }
};

</script>

<style scoped>
</style>
